package com.yun.reggie.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.IdWorker;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.yun.reggie.common.BaseContext;
import com.yun.reggie.common.CustomException;
import com.yun.reggie.dto.OrdersDto;
import com.yun.reggie.entity.*;
import com.yun.reggie.mapper.OrdersMapper;
import com.yun.reggie.service.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;
import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.atomic.AtomicInteger;

/**
 * @author xiao
 */
@Service
public class OrdersServiceImpl extends ServiceImpl<OrdersMapper, Orders> implements OrdersService {

    @Autowired
    private ShoppingCartService shoppingCartService;

    @Autowired
    private UserService userService;

    @Autowired
    private AddressBookService addressBookService;

    @Autowired
    private OrderDetailService orderDetailService;

    /**
     *  事务控制
     * 保存订单
     * 1.保存订单基础信息，保存到订单表(插入一条数据)
     * 1.1 填充订单基础信息(收货地址)
     * 2.查询购物车信息，保存到订单详情表(可以插入多条数据)
     * 3.清除购物车信息
     * @param orders
     */
    @Override
    public void saveOrder(Orders orders) {
        Long userId = BaseContext.getCurrentId();
        //查询购物车信息
        LambdaQueryWrapper<ShoppingCart> shoppingCartWrapper = new LambdaQueryWrapper<>();
        shoppingCartWrapper.eq(ShoppingCart::getUserId,userId);
        List<ShoppingCart> shoppingCartList = shoppingCartService.list(shoppingCartWrapper);
        if (shoppingCartList == null || shoppingCartList.size() == 0){
            throw new CustomException("购物车为空，下单失败！");
        }

        //查询用户信息--用户名
        User user = userService.getById(userId);

        //查询地址信息
        AddressBook addressBook = addressBookService.getById(orders.getAddressBookId());
        if (addressBook == null){
            throw new CustomException("地址信息有误，下单失败！");
        }

        //设置订单表基础信息,待付款，下单时间,订单号,用户名，地址信息
        orders.setStatus(1);
        orders.setOrderTime(LocalDateTime.now());
        orders.setCheckoutTime(LocalDateTime.now());
        orders.setUserName(user.getName());
        //注意：设置订单号number.由后端生成，而不是数据库生成
        long orderId = IdWorker.getId();
        orders.setId(orderId);
        orders.setNumber(String.valueOf(orderId));
        orders.setUserId(userId);
        orders.setAddressBookId(addressBook.getId());
        //设置收货人信息
        orders.setPhone(addressBook.getPhone());
        orders.setConsignee(addressBook.getConsignee());
        //将地址中的省市区拼接起来
        orders.setAddress((addressBook.getProvinceName() == null ? "" : addressBook.getProvinceName())
                + (addressBook.getCityName() == null ? "" : addressBook.getCityName())
                + (addressBook.getDistrictName() == null ? "" : addressBook.getDistrictName())
                + (addressBook.getDetail() == null ? "" : addressBook.getDetail()));
        //计算订单的金额和订单明细，遍历购物车
        List<OrderDetail> orderDetailList = new ArrayList<>();
        //AtomicInteger原子操作类，保证多线程环境下操作数据不会出错
        AtomicInteger atomicInteger = new AtomicInteger(0);
        for (ShoppingCart shoppingCart:shoppingCartList) {
            OrderDetail orderDetail = new OrderDetail();
            orderDetail.setName(shoppingCart.getName());
            orderDetail.setOrderId(orderId);
            orderDetail.setDishId(shoppingCart.getDishId());
            orderDetail.setSetmealId(shoppingCart.getSetmealId());
            orderDetail.setDishFlavor(shoppingCart.getDishFlavor());
            orderDetail.setNumber(shoppingCart.getNumber());
            orderDetail.setAmount(shoppingCart.getAmount());
            orderDetail.setImage(shoppingCart.getImage());
            //计算金额(金额*份数转化为int,循环累加)
            atomicInteger.addAndGet(shoppingCart.getAmount().multiply(new BigDecimal(shoppingCart.getNumber())).intValue());
            orderDetailList.add(orderDetail);
        }
        //设置订单金额
        orders.setAmount(new BigDecimal(atomicInteger.get()));
        super.save(orders);
        orderDetailService.saveBatch(orderDetailList);
        //清空购物车
        shoppingCartService.remove(shoppingCartWrapper);
    }
}
